import datetime
import queue
import logging
import signal
import time
import threading
import tkinter as tk
from tkinter import filedialog
from tkinter.scrolledtext import ScrolledText
from tkinter import ttk, VERTICAL, HORIZONTAL, N, S, E, W

from mkpdf import *

softName = 'FFBook'
version  = 'v0.1'

logger = logging.getLogger(__name__)

class QueueHandler(logging.Handler):
    """Class to send logging records to a queue

    It can be used from different threads
    The ConsoleUi class polls this queue to display records in a ScrolledText widget
    """
    # Example from Moshe Kaplan: https://gist.github.com/moshekaplan/c425f861de7bbf28ef06
    # (https://stackoverflow.com/questions/13318742/python-logging-to-tkinter-text-widget) is not thread safe!
    # See https://stackoverflow.com/questions/43909849/tkinter-python-crashes-on-new-thread-trying-to-log-on-main-thread

    def __init__(self, log_queue):
        super().__init__()
        self.log_queue = log_queue

    def emit(self, record):
        self.log_queue.put(record)


class ConsoleUi:
    """Poll messages from a logging queue and display them in a scrolled text widget"""

    def __init__(self, frame):
        self.frame = frame
        # Create a ScrolledText wdiget
        self.text_options = {"state": "disabled",
                             "bg": "white",
                             "height": 50,
                             "width": 100,
                             "fg": "#08c614",
                             "insertbackground": "#08c614",
                             "selectbackground": "#f01c1c"}
        self.scrolled_text = ScrolledText(frame, **self.text_options)
        #self.scrolled_text = ScrolledText(frame, state='disabled', height=12)
        self.scrolled_text.grid(row=0, column=0, sticky=(N, S, W, E))
        self.scrolled_text.configure(font='TkFixedFont')
        self.scrolled_text.tag_config('INFO', foreground='black')
        self.scrolled_text.tag_config('DEBUG', foreground='gray')
        self.scrolled_text.tag_config('WARNING', foreground='#006400')
        self.scrolled_text.tag_config('ERROR', foreground='red')
        self.scrolled_text.tag_config('CRITICAL', foreground='red', underline=1)
        # Create a logging handler using a queue
        self.log_queue = queue.Queue()
        self.queue_handler = QueueHandler(self.log_queue)
        formatter = logging.Formatter('%(asctime)s: %(message)s')
        self.queue_handler.setFormatter(formatter)
        logger.addHandler(self.queue_handler)
        # Start polling messages from the queue
        self.frame.after(100, self.poll_log_queue)

    def display(self, record):
        msg = self.queue_handler.format(record)
        self.scrolled_text.configure(state='normal')
        self.scrolled_text.insert(tk.END, msg + '\n', record.levelname)
        self.scrolled_text.configure(state='disabled')
        # Autoscroll to the bottom
        self.scrolled_text.yview(tk.END)

    def poll_log_queue(self):
        # Check every 100ms if there is a new message in the queue to display
        while True:
            try:
                record = self.log_queue.get(block=False)
            except queue.Empty:
                break
            else:
                self.display(record)
        self.frame.after(100, self.poll_log_queue)


class FormUi:

    def __init__(self, frame, root, callback):
        self.frame = frame
        self.root  = root
        self.srcRoot = ''
        self.callback = callback
        self.outRoot = os.path.join(os.path.dirname(os.path.abspath(__file__))\
                , 'out')
        self.tasks = 1
        # Create a combobbox to select the tasks
        values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        self.level = tk.StringVar()
        ttk.Label(self.frame, text='任务数:').grid(column=0, row=0, sticky=W)
        self.combobox = ttk.Combobox(
            self.frame,
            textvariable=self.level,
            width=5,
            state='readonly',
            values=values
        )
        self.combobox.current(0)
        self.combobox.grid(column=1, row=0, sticky=(W, E))
        # Create a text field to enter a message
        self.message = tk.StringVar()
        self.path = tk.StringVar()
        #self.path.set('此处选择视频所在目录')

        ttk.Label(self.frame, text='选择视频所在目录:').grid(column=0, row=1, sticky=W)
        #ttk.Entry(self.frame, textvariable = self.path, state='readonly').grid(row = 1, column=0)
        self.btn_open = tk.Button(self.frame, text="选择目录", command=self.open_dir)
        #ttk.btn_open.pack(side="left", padx=5, pady=2)
        self.btn_open.grid(column=1, row=1, sticky=W)
        # Add a button to log the message
        self.button = ttk.Button(self.frame, text='开始', command=self.submit_message)
        self.button.grid(column=1, row=2, sticky=W)


    def submit_message(self):
        # Get the logging level numeric value
        if not os.path.exists(self.srcRoot):
            logger.log(logging.ERROR, '请选择正确的路径先!')
            return

        self.bt_switch()
        thread = threading.Thread(target=self.callback, args=(self,))
        thread.start()
        pass

    def bt_switch(self):
        #print(self.button['state'], self.button['text'], tk.NORMAL)
        #print(type(self.button['state']), self.button['text'], type(tk.NORMAL))
        if str(self.button['state']) == tk.NORMAL:
            self.button["state"] = "disabled"
            self.button["text"] = "执行中"
        else:
            self.button["state"] = "normal"
            self.button["text"] = "开始"

    def open_dir(self):
        """Open a file for editing."""
        path = filedialog.askdirectory()
        if sys.platform == 'win32':
            path = path.replace('/', '\\')
        self.path.set(path)
        if not path:
            return
        thread = threading.Thread(target=self.callback, args=(self,))
        self.srcRoot = path
        #self.text.delete(1.0, tk.END)
        #with open(path, "r") as input_file:
        #    text = input_file.read()
        #    self.text.insert(tk.END, text)
        logger.info(f'待处理目录：{path}')
        self.root.title(f"{softName} {version} - 正在处理{path}")

    def get_conf(self):
        self.tasks = self.level.get()
        return self.srcRoot, self.outRoot, self.tasks

    def cmsg(self, msg):
        logger.info(msg)

    def gmsg(self, msg):
        logger.warning(msg)


class ThirdUi:

    def __init__(self, frame):
        self.frame = frame
        ttk.Label(self.frame, text='').grid(column=0, row=1, sticky=W)


class App:

    def __init__(self, root, callback):
        self.root = root
        root.title(f'{softName} {version}')
        root.columnconfigure(0, weight=1)
        root.rowconfigure(0, weight=1)
        # Create the panes and frames
        vertical_pane = ttk.PanedWindow(self.root, orient=VERTICAL)
        vertical_pane.grid(row=0, column=0, sticky="nsew")
        horizontal_pane = ttk.PanedWindow(vertical_pane, orient=HORIZONTAL)
        vertical_pane.add(horizontal_pane)
        form_frame = ttk.Labelframe(horizontal_pane, text="")
        form_frame.columnconfigure(1, weight=1)
        horizontal_pane.add(form_frame, weight=1)
        console_frame = ttk.Labelframe(horizontal_pane, text="日志")
        console_frame.columnconfigure(0, weight=1)
        console_frame.rowconfigure(0, weight=1)
        horizontal_pane.add(console_frame, weight=1)
        third_frame = ttk.Labelframe(vertical_pane,
                text=f"发现任何问题请联系：bsdcpp@gmail.com，谢谢！")
        vertical_pane.add(third_frame, weight=1)
        # Initialize all frames
        self.form = FormUi(form_frame, root, callback)
        self.console = ConsoleUi(console_frame)
        self.third = ThirdUi(third_frame)
        self.root.protocol('WM_DELETE_WINDOW', self.quit)
        self.root.bind('<Control-q>', self.quit)
        signal.signal(signal.SIGINT, self.quit)

    def quit(self, *args):
        self.root.destroy()

def mkpdf_task(obj):
    ffbook = FFBook()
    srcRoot, outRoot, tasks = obj.get_conf()
    ffbook.set_conf(srcRoot, outRoot, tasks)
    logger.info('任务开始!')
    logger.info(f'处理目录: {srcRoot}')
    logger.info(f'任务数: {tasks}')

    logger.warning("开始处理视频文件，请耐心等待......")
    # 检查目录是否有字幕文件，没有则尝试从视频文件获取
    ffbook.check_sub()
    # 开始执行主要任务
    result = ffbook.main_task(obj)
    if result:
        logger.warning("恭喜你，全部处理完毕！")
        logger.info(f'输出文件: ')
        for f in result:
            logger.warning(f'{f}')
    else:
        logger.error('处理出现问题，没有生成文件，可能是不存在字幕，文件名不标准。')

    obj.bt_switch()

def main():
    #logging.basicConfig(level=logging.DEBUG)
    logging.basicConfig(filename='log.txt',
                            filemode='a',
                            format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                            datefmt='%H:%M:%S',
                            level=logging.DEBUG)
    root = tk.Tk()
    app = App(root, mkpdf_task)
    app.root.mainloop()

if __name__ == '__main__':
    main()
